package com.xincheng.shuimalong.activity.mydetail.wallet;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xincheng.library.util.DateUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.widget.pickerview.TimePickerView;
import com.xincheng.library.xswipemenurecyclerview.holder.RecyclerHolder;
import com.xincheng.library.xswipemenurecyclerview.listener.OnItemClickListener;
import com.xincheng.library.xswipemenurecyclerview.recycler.MRecyclerView;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.bank.BankCardAddActivity;
import com.xincheng.shuimalong.activity.bank.MyBankCardActivity;
import com.xincheng.shuimalong.adapter.wallet.MoneyLogAdapter;
import com.xincheng.shuimalong.adapter.wallet.WalletInquiryAdapter;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.OrderConfig;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.wallet.MoneyLogDetail;
import com.xincheng.shuimalong.entity.wallet.WalletInquiry;
import com.xincheng.shuimalong.entity.wallet.MoneyLog;
import com.xincheng.shuimalong.util.CalenderUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 许浩 on 2017/6/19.
 */

public class WalletActivity extends BaseActivity {
    @BindView(R.id.wallet_header_layout)
    RelativeLayout mHeadLayout;
    @BindView(R.id.wallet_money_tv)
    TextView mMoneyTv;
    @BindView(R.id.wallet_log_rv)
    MRecyclerView mMoneyLogRv;
    @BindView(R.id.wallet_total_increase_tv)
    TextView mTotalIncreaseTv;
    @BindView(R.id.wallet_total_reduce_tv)
    TextView mTotalReduceTv;
    @BindView(R.id.wallet_date_interval_tv)
    TextView mDateIntervalTv;

    @BindView(R.id.wallet_inquiry_layout)
    LinearLayout mInuqiryLayout;
    @BindView(R.id.wallet_inquiry_startdate_layout)
    LinearLayout mStartDateLayout;
    @BindView(R.id.wallet_inquiry_enddate_layout)
    LinearLayout mEndDateLayout;
    @BindView(R.id.wallet_inquiry_startdate_tv)
    TextView mStartDateTv;
    @BindView(R.id.wallet_inquiry_enddate_tv)
    TextView mEndDateTv;
    @BindView(R.id.wallet_inquiry_popup_mrv)
    MRecyclerView mInquiryRv;

    private String myTotalMoney;
    private String mToken;
    private MoneyLogAdapter mAdapter;

    private WalletInquiryAdapter mInquiryAdapter;

    private int mType = 0;
    private String mStartDate = "";
    private String mEndDate = "";
    private Calendar mStartCalender, mEndCalender;

    private TimePickerView mStartDatePicker, mEndDatePicker;
    private long mStartDateTime, mEndDateTime;
    private boolean mWithdrawSuccess;
    private int mOrderConfig;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_my_wallet;
    }

    @Override
    public void initData() {
        mWithdrawSuccess = false;
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        myTotalMoney = extras.getString(IntentKey.TOTAL_MONEY);
        mOrderConfig = extras.getInt(IntentKey.ORDER_CONFIG);
        mMoneyTv.setText(myTotalMoney);
        mMoneyLogRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MoneyLogAdapter(this);
        mMoneyLogRv.setAdapter(mAdapter);
        initInquiry();
        initCalendar();
        initDate();
        initPickerView();
        getMyMoneyLog();
    }

    private void initCalendar() {
        mStartCalender = Calendar.getInstance();
        mStartCalender.set(mStartCalender.get(Calendar.YEAR), mStartCalender.get(Calendar.MONTH),
                mStartCalender.get(Calendar.DAY_OF_MONTH) - 7);
        mEndCalender = Calendar.getInstance();
        mDateIntervalTv.setText(DateUtil.parseDate(mStartCalender.getTime()) + "~" +
                DateUtil.parseDate(mEndCalender.getTime()));
    }

    private void initInquiry() {
        mInquiryRv.setLayoutManager(new LinearLayoutManager(this));
        List<WalletInquiry> list = new ArrayList<>();
        String[] inquiryArr = null;
        switch (mOrderConfig) {
            case OrderConfig.RECEIPT:
                inquiryArr = getResources().getStringArray(R.array.wallet_inqury_receipt);
                break;
            case OrderConfig.SELL:
                inquiryArr = getResources().getStringArray(R.array.wallet_inqury_sell);
                break;
        }
        for (int i = 0; i < inquiryArr.length; i++) {
            WalletInquiry walletInquiry = new WalletInquiry();
            walletInquiry.setId(i + 1);
            walletInquiry.setName(inquiryArr[i]);
            walletInquiry.setSelected(i == 0 ? true : false);
            list.add(walletInquiry);
        }
        mInquiryAdapter = new WalletInquiryAdapter(this, list);
        mInquiryRv.setAdapter(mInquiryAdapter);
    }

    private void initDate() {
        mStartDate = DateUtil.parseDate(mStartCalender.getTime());
        mEndDate = DateUtil.parseDate(mEndCalender.getTime());
        mStartDateTime = mStartCalender.getTimeInMillis();
        mEndDateTime = mEndCalender.getTimeInMillis();
        mStartDateTv.setText(mStartDate);
        mEndDateTv.setText(mEndDate);
    }

    private void initPickerView() {
        mStartDatePicker = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mStartDateTime = date.getTime();
                mStartDate = DateUtil.parseDate(date);
                mStartDateTv.setText(mStartDate);
            }
        }).setDate(mStartCalender).setRangDate(CalenderUtil.getRangeStartDate(), CalenderUtil.getRangeEndDate())
                .setLabel("年", "月", "日", null, null, null)
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCyclic(true).isCenterLabel(false)
                .build();
        mEndDatePicker = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mEndDateTime = date.getTime();
                if (mEndDateTime < mStartDateTime) {
                    mEndDatePicker.setCanDismiss(false);
                    showToast("结束时间不能小于开始时间");
                    return;
                }
                mEndDatePicker.setCanDismiss(true);
                mEndDate = DateUtil.parseDate(date);
                mEndDateTv.setText(mEndDate);
            }
        }).setDate(mEndCalender).setRangDate(CalenderUtil.getRangeStartDate(), CalenderUtil.getRangeEndDate())
                .setLabel("年", "月", "日", null, null, null)
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCyclic(true).isCenterLabel(false)
                .build();
    }

    @Override
    public void addListener() {
        mMoneyLogRv.setOnItemClickListener(new MyOnItemClickListener());
        mInquiryRv.setOnItemClickListener(new WalletInquiryItemClickListener());
    }

    @OnClick({R.id.wallet_back_iv, R.id.wallet_bankcard_iv, R.id.wallet_bankcard_my_tv,
            R.id.wallet_withdraw_deposit_tv, R.id.wallet_inquiry_tv, R.id.wallet_header_layout,
            R.id.wallet_inquiry_layout, R.id.wallet_inquiry_startdate_layout,
            R.id.wallet_inquiry_enddate_layout, R.id.wallet_inquiry_cancel_tv,
            R.id.wallet_inquiry_confirm_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.wallet_back_iv://返回
                if (mInuqiryLayout.getVisibility() == View.VISIBLE) {
                    mInuqiryLayout.setVisibility(View.GONE);
                } else {
                    if (mWithdrawSuccess) {
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.WITHDRAW_SUCCESS, true);
                        setResult(RESULT_OK, intent);
                        finish();
                        return;
                    }
                    finish();
                }
                break;
            case R.id.wallet_bankcard_iv://我的银行卡
                if (mInuqiryLayout.getVisibility() == View.VISIBLE) {
                    mInuqiryLayout.setVisibility(View.GONE);
                } else {
                    ShowActivity.showActivity(this, BankCardAddActivity.class);
                }
                break;
            case R.id.wallet_bankcard_my_tv:
                ShowActivity.showActivity(this, MyBankCardActivity.class);
                break;
            case R.id.wallet_withdraw_deposit_tv://提现
                Bundle extras = new Bundle();
                extras.putString(IntentKey.TOTAL_MONEY, myTotalMoney);
                ShowActivity.showActivityForResult(this, WithdrawDepositActivity.class, extras,
                        RequestCodeKey.GO_DESPOSE);
                break;
            case R.id.wallet_inquiry_tv://查询
                mInuqiryLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.wallet_header_layout:
                mInuqiryLayout.setVisibility(View.GONE);
                break;
            case R.id.wallet_inquiry_layout:
                mInuqiryLayout.setVisibility(View.GONE);
                break;
            case R.id.wallet_inquiry_startdate_layout:
                if (mStartDatePicker != null) {
                    mStartDatePicker.show();
                }
                break;
            case R.id.wallet_inquiry_enddate_layout:
                if (mEndDatePicker != null) {
                    mEndDatePicker.show();
                }
                break;
            case R.id.wallet_inquiry_cancel_tv:
                mInuqiryLayout.setVisibility(View.GONE);
                break;
            case R.id.wallet_inquiry_confirm_tv:
                mInuqiryLayout.setVisibility(View.GONE);
                mDateIntervalTv.setText(mStartDate + "~" + mEndDate);
                getMyMoneyLog();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_DESPOSE:
                    mWithdrawSuccess = data.getBooleanExtra(IntentKey.WITHDRAW_SUCCESS, false);
                    myTotalMoney = data.getStringExtra(IntentKey.TOTAL_MONEY);
                    mMoneyTv.setText(myTotalMoney);
                    getMyMoneyLog();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void getMyMoneyLog() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.myMoneyLog(mToken, mType,
                mStartDate, mEndDate) ,
                new BaseObserver(this, getString(R.string.loading_data)) {
            @Override
            protected void onHandleSuccess(Object data, String msg) {
                MoneyLog moneyLog = GsonUtil.parseData(data, MoneyLog.class);
                mTotalIncreaseTv.setText(getString(R.string.total_increase,
                        moneyLog.getTotalIncrease()));
                mTotalReduceTv.setText(getString(R.string.total_reduce,
                        moneyLog.getTotalReduce()));
                List<MoneyLog.Data> dataList = moneyLog.getLogList();
                mAdapter.refreshData(dataList);
            }
        });
    }

    private class MyOnItemClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(RecyclerHolder holder, View view, int position) {
            MoneyLog.Data data = mAdapter.getItem(position);
            Bundle extras = new Bundle();
            extras.putString(IntentKey.LOG_ID, data.getLogId());
            extras.putInt(IntentKey.LOG_TYPE, data.getType());
            extras.putInt(IntentKey.LOG_REDUCE_STATUS, data.getReduceStatus());
            ShowActivity.showActivity(getContext(), MoneyLogDetailActivity.class, extras);
        }
    }

    private class WalletInquiryItemClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(RecyclerHolder holder, View view, int position) {
            mInquiryAdapter.changeSelect(position);
            WalletInquiry walletInquiry = mInquiryAdapter.getItem(position);
            switch (walletInquiry.getId()) {
                case 1:
                    mType = 0;
                    break;
                case 2:
                    switch (mOrderConfig) {
                        case OrderConfig.RECEIPT:
                            mType = 5;
                            break;
                        case OrderConfig.SELL:
                            mType = 3;
                            break;
                    }
                    break;
                case 3:
                    mType = 6;
                    break;
                case 4:
                    mType = 99;
                    break;
            }
        }
    }

}
